import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MasterService2 {

  protected static final Logger log = LoggerFactory.getLogger(MasterService2.class);

  private CuratorFramework client;
  public static final String ROOT = "/gunode";
  public static final String MASTER_NODE = ROOT + "/master";

  public MasterService2() {
    client = CuratorFrameworkFactory.builder().connectString("gcb.aliyun.com:2181")
        .retryPolicy(new RetryNTimes(1, 1000))
        .build();
    client.start();

    try {
      initRoot();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void initRoot() throws Exception {
    String rootPath = ROOT;
    Stat stat = client.checkExists().forPath(rootPath);
    if (stat == null) {
      log.info("init root path {}", rootPath);
      client.create().forPath(rootPath);
    }
  }

  public void electMaster(LeaderSelectorListener listener) {
    LeaderSelector selector = new LeaderSelector(client, MASTER_NODE, listener);
//    selector.autoRequeue();
    selector.start();
  }

  public void subscribe(String masterNode, Node node,
      MasterListener listener) throws Exception {
    System.out.println("subscribe master");
    client.getChildren().usingWatcher((CuratorWatcher) event -> listener.whenDown(node))
        .forPath(masterNode);
  }

  public void close() {
    try {
      if (client.checkExists().forPath(MASTER_NODE) != null) {
        client.delete().forPath(MASTER_NODE);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
